#include "tcpserver.hpp"
#include "Json.hpp"

using namespace Protocal;

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " serverip serverport\n"
              << std::endl;
}

class Factory
{
private:
    string opers;
public:

    Factory()
    {
        opers = "+-/*%";
        srand((unsigned int)time(nullptr));
    }

    shared_ptr<Request> BuildInfo()
    {
        shared_ptr<Request> ptr = make_shared<Request>();
        ptr->_x = rand() % 10;
        ptr->_y = rand() % 10;
        ptr->_oper = opers[rand() % opers.size()];

        return ptr;
    }

};

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    string serverip = argv[1];
    int serverport = stoi(argv[2]);

    Analyze addr(serverip, serverport);

    unique_ptr<Socket> ptr = make_unique<TcpSocket>();
    ptr->BuildTcpClientSocket(addr);
    
    Factory fact;
    string str_recv;
    while(true)
    {
        sleep(1);
        shared_ptr<Request> info = fact.BuildInfo();
        string str_send = info->Serislize();

        Encode(str_send);
        ptr->Send(str_send);
   
        int ret = ptr->Recv(str_recv);
        if(ret <= 0) break;

        string package = Decode(str_recv);
        if(package.empty()) continue;

        Response resp;
        resp.DeSerislize(package);
        cout << "ret: " << resp._ret << "code: " << resp._code << endl;
    }

    return 0;
}
